package com.sgb.kjwl.view.ui.fragment.transport.company;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.viewpager2.widget.ViewPager2;

import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentFeetManageBinding;
import com.sgb.kjwl.model.entity.transport.TabEntity;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.event.self.GoodsManageEvent;
import com.sgb.kjwl.view.ui.adapter.self.logistics.SimpleFragmentAdapter;
import com.sgb.kjwl.view.ui.adapter.transport.LinkedFleetTabAdapter;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * author:熊丽
 * createDate:2021/10/9 10:42
 * introduce:自营车队管理列表和挂靠车队
 * modifier:xxx
 * modifiyDate:
 * modifiyContent:
 */
public class LinkedFleetFragment extends AppLazyFragment {

    FragmentFeetManageBinding binding;
    private final List<Fragment> mFragments = new ArrayList<>();
    private List<TabEntity> mTabs;
    private LinkedFleetTabAdapter mAdapter;
    private boolean mIsLinked = false;
    //是否需要刷新全部数据，接收事件后使用
    private boolean mIsNeedRefreshAll = false;

    public static LinkedFleetFragment newInstance(boolean isLinked) {
        LinkedFleetFragment fragment = new LinkedFleetFragment();
        Bundle args = new Bundle();
        args.putBoolean(RouterKey.BOOLEAN, isLinked);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_feet_manage, container, false);
        binding.setLifecycleOwner(this);
        return binding.getRoot();
    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (getArguments() != null) {
            mIsLinked = getArguments().getBoolean(RouterKey.BOOLEAN, true);
        }
        initTab();
        initEvent();
    }

    @Override
    protected void onLazyLoad() {
        initFragment();
    }

    private void initTab() {
        mTabs = new ArrayList<>();
        mTabs.add(new TabEntity("全部"));
        mTabs.add(new TabEntity("邀请中", true, 0, 99));
        mTabs.add(new TabEntity("已同意"));
        mTabs.add(new TabEntity("已拒绝"));
        mTabs.add(new TabEntity("已解除"));
        mAdapter = new LinkedFleetTabAdapter(mTabs);
//        binding.rvCargoManageTab.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.HORIZONTAL, false));
//        binding.rvCargoManageTab.setAdapter(mAdapter);
        binding.rvCargoManageTab.setLayoutManager(new GridLayoutManager(getContext(), 5));
        binding.rvCargoManageTab.setAdapter(mAdapter);
    }

    private void initEvent() {
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            mAdapter.setSelectIndex(position);
            binding.vpCargoManage.setCurrentItem(position);
        });
        binding.vpCargoManage.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                mAdapter.setSelectIndex(position);
                ((LinearLayoutManager) binding.rvCargoManageTab.getLayoutManager()).scrollToPosition(position);
            }
        });
    }

    private void initFragment() {
        for (int i = 0; i < mTabs.size(); i++) {
            mFragments.add(ProprietaryAndLinkItemFragment.newInstance(getRequestStateByTabPosition(i), mIsLinked));
        }
        SimpleFragmentAdapter fragmentAdapter = new SimpleFragmentAdapter(getActivity(), mFragments);
        binding.vpCargoManage.setAdapter(fragmentAdapter);
        binding.vpCargoManage.setOffscreenPageLimit(mTabs.size());
    }

    private int getRequestStateByTabPosition(int tabPosition) {
        //todo 状态待调整
        //查询状态 0待接单 3付款中 4 报价已截止 5 已下架 6其他
        int state = -1;
            switch (tabPosition) {
                case 0:
                    state = 0;
                    break;
                case 1:
                    state = 1;
                    break;
                case 2:
                    state = 3;
                    break;
                case 3:
                    state = 2;
                    break;
                case 4:
                    state = 4;
                    break;
            }
        return state;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateCount(GoodsManageEvent event) {
        //货源管理页面事件
        if (event.getMessageTag() == EventConstant.EVENT_REFRESH_CARGO_MANAGE_TAB_COUNT) {
                updateCount((Integer) event.getMessageData());
        }else if (event.getMessageTag() == EventConstant.EVENT_REFRESH_AFFILIATED_SUCCESS) {
            refreshAllData();
        }
    }
    private void refreshAllData() {
        for (int i = 0; i < mFragments.size(); i++) {
            ((ProprietaryAndLinkItemFragment) mFragments.get(i)).refreshData();
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void goodsChangeEvent(LogisticsEvent event) {
        //其他页面事件
        switch (event.getMessageTag()) {
            case EventConstant.EVENT_CARGO_RELEASE_SUCCESS:
            case EventConstant.EVENT_GOOD_DETAIL_DELETE:
            case EventConstant.EVENT_GOOD_DETAIL_UP_AND_DOWN_SUCCESS:
            case EventConstant.EVENT_GOODS_AGREED_OFFER:
            case EventConstant.EVENT_REFRESH_OFFER_OWNER_PAGE:
                mIsNeedRefreshAll = true;
                break;
        }
    }
    public void updateCount(int count) {
        if (mAdapter != null && mTabs != null && mTabs.size() > 2) {
            mTabs.get(1).setNumber(count);
            mAdapter.notifyDataSetChanged();
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        if (mIsNeedRefreshAll){
            mIsNeedRefreshAll = false;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
